#coding:utf-8

from Libs.ServerLib import monitor_process
from Node.Achieve import test
import os
import importlib
import subprocess
import time

# from FuzzCore.wfuzz.wfuzz import fuzz
# from FuzzCore.boofuzz.fuzz_logger_db import FuzzLoggerDbReader

class Test:
    def __init__(self):
        self.run_info = {}
        self.import_str = None

    def importFuzz(self,plugin_name,load_dict):
        plugin_name = 'Plugin.%s' % plugin_name  #"from Plugin.%s import *" % plugin_name
        #print(plugin_name)
        self.import_str = importlib.import_module(plugin_name)
        self.load_dict = load_dict

    def boofuzzRun(self, process_name, cmd=""):
        self.run_info[process_name] = {}
        self.run_info[process_name]['isrun'] = False
        if cmd == "":
            pid_ = monitor_process(process_name)
            print(pid_)
            if pid_ == None:
                return False

            self.run_info[process_name]['p'] = None
            self.run_info[process_name]['cmd'] = cmd
            self.run_info[process_name]['pid'] = pid_
            self.run_info[process_name]['isrun'] = True
            self.run_info[process_name]['runtime'] = 0
            self.run_info[process_name]['poll'] = None
        else:
            p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=False, shell=True)
            self.run_info[process_name]['p'] = p
            self.run_info[process_name]['cmd'] = cmd
            self.run_info[process_name]['pid'] = p.pid
            self.run_info[process_name]['isrun'] = True
            self.run_info[process_name]['runtime'] = time.time()
            self.run_info[process_name]['poll'] = p.poll()

        #print(self.run_info[process_name]['pid'])
        start = self.import_str.Fuzz()
        start.Run(self.load_dict)

        return True

    def boofuzzStat(self, process_name):
        process = self.run_info[process_name]
        print(process['pid'])
        print(process['poll'])
        p = process['poll']
        process['p'].kill()




# def monitor_process(key_word):
#     p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
#     p2 = subprocess.Popen(['grep', key_word], stdin=p1.stdout, stdout=subprocess.PIPE)
#     p3 = subprocess.Popen(['grep', '-v', 'grep'], stdin=p2.stdout, stdout=subprocess.PIPE)
#     lines = p3.stdout.readlines()
#     if len(lines) > 0:
#         return None
#
#     return str(lines).split(" ")[3]
#


if __name__ == "__main__":
    print(os.getcwd())
    test()
    # test = Test()
    # test.importFuzz("ftp",{'host': '127.0.0.1', 'port': 21, 'proto': 'tcp', 'user': 'anonymous', 'pass': 'anonymous','core':'boofuzz'})
    # test.boofuzzRun("rumpusd")
    # monitor_process("66489")